package com.breadenglish.cms.api.app.sys.service.impl;

import com.breadenglish.cms.api.app.dao.CodeClassDao;
import com.breadenglish.cms.api.app.domain.constants.Constants;
import com.breadenglish.cms.api.app.domain.constants.MessageConstants;
import com.breadenglish.cms.api.app.domain.db.CodeClass;
import com.breadenglish.cms.api.app.domain.exception.BusinessException;
import com.breadenglish.cms.api.app.domain.query.CodeClassQuery;
import com.breadenglish.cms.api.app.sys.service.CodeClassService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 字典分类管理处理接口
 * User: guoyao
 * Date: 2013-12-17
 * Time: 09:30
 */
@Service("codeClassService")
public class CodeClassServiceImpl implements CodeClassService {

    private final static Logger logger = LoggerFactory.getLogger(CodeClassServiceImpl.class);

    @Resource
    private CodeClassDao codeClassDao;

    /**
     * 字典分类查询
     *
     * @param codeClass 字典分类信息
     * @return 字典分类信息集合
     */
    @Override
    public List<CodeClassQuery> queryCodeClasses(CodeClass codeClass) throws Throwable {
        return codeClassDao.select(codeClass);
    }

    /**
     * 查询字典详情信息
     *
     * @param codeClassId 字典分类ID
     * @return 字典分类详情信息
     */
    @Override
    public CodeClass queryCodeClass(String codeClassId) throws Throwable {
        return codeClassDao.selectByPrimaryKey(codeClassId);
    }

    /**
     * 查询生成下拉菜单的字典分类信息
     *
     * @param codeClass 字典分类信息
     * @return 字典分类信息
     */
    public List<CodeClass> queryCodeClasssForSelectMenu(CodeClass codeClass) throws Throwable {
        return codeClassDao.selectForm(codeClass);
    }

    /**
     * 添加字典分类
     *
     * @param codeClass 字典分类信息
     * @return 影响行数
     */
    @Override
    public void insertCodeClass(CodeClass codeClass) throws Throwable {
        // 字典类别(classId)验证 唯一性
        uniqueClassId(codeClass.getClassId());
        logger.debug("字典分类唯一性验证通过，没有异常抛出");
        //执行添加
        codeClass.setCreateTime(new Date());
        int result = codeClassDao.insert(codeClass);
        if (result != 1) {
            logger.debug("新增字典分类失败，准备抛出异常");
            BusinessException businessException = new BusinessException();
            businessException.setCode(MessageConstants.INSERT_CODE_CLASS_FAIL);
            throw businessException;
        }
    }

    /**
     * 根据字典分类ID更新字典分类信息
     *
     * @param codeClass 字典分类信息
     * @return 影响行数
     */
    @Override
    public void updateCodeClass(CodeClass codeClass) throws Throwable {
        codeClass.setUpdateTime(new Date());
        int result = codeClassDao.update(codeClass);
        if (result != 1) {
            BusinessException businessException = new BusinessException();
            businessException.setCode(MessageConstants.UPDATE_CODE_CLASS_FAIL);
            throw businessException;
        }
    }

    /**
     * 根据字典分类ID删除字典分类信息
     *
     * @param codeClass 字典分类ID
     * @return 影响行数
     */
    @Override
    public void deleteCodeClass(CodeClass codeClass, String codeClassIds) throws Throwable {
        // TODO 批量删除字符串分隔符 X
        String[] codeClassId = codeClassIds.split(":");
        int idLen = codeClassId.length;
        logger.debug("codeClassId.length() => " + idLen);

        List<String[]> errors = new ArrayList<String[]>();

        if (idLen == 0) {
            BusinessException businessException = new BusinessException();
            businessException.setCode(MessageConstants.DELETE_CODE_CLASS_UNSELECTED);
            throw businessException;
        }

        int sucNum = 0;
        codeClass.setDelTag(Constants.YES);
        codeClass.setUpdateTime(new Date());

        String[] errorMsg = new String[2];
        // TODO 删除提示信息，采用占位符替换功能 X
        errorMsg[0] = "失败ID: \n";

        for (int i = 0; i < idLen; i++) {
            codeClass.setClassId(codeClassId[i]);
            int result = codeClassDao.update(codeClass);

            if (result == 0) {
                errorMsg[0] = errorMsg[0] + "  \t " + codeClassId[i] + "\n";
            }

            sucNum += result;
        }

        if (sucNum != idLen) {
            BusinessException businessException = new BusinessException();
            if (sucNum < idLen && sucNum > 0) {
                errorMsg[1] = "成功删除: " + sucNum + " 条 \n";
            }

            if (sucNum > idLen) {
                errorMsg[1] = "预期删除: " + idLen + " 条, 实际删除: " + sucNum + " 条\n";
            }
            if (sucNum == 0) {
                errorMsg[1] = "\n删除失败";
            }
            errors.add(errorMsg);
            businessException.setKeys(errors);
            businessException.setCode(MessageConstants.DELETE_FAIL);
            throw businessException;
        }
    }

    /**
     * 验证字典分类ID是否唯一
     *
     * @param classId 字典分类ID
     * @Return 查询结果
     */
    public void uniqueClassId(String classId) throws Throwable {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        //resultMap.put("state", false);
        int countNum = codeClassDao.uniqueClassId(classId);
        if (countNum > 0) {
            logger.debug("字典分类唯一性验证: 字典分类已经存在，准备抛出异常");
            BusinessException businessException = new BusinessException();
            businessException.setCode(MessageConstants.CODE_CLASS_UNIQUE_CHECK_FAIL);
            throw businessException;
        }
    }


}
